package com.engine.salary.web;

import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.taxdeclaration.dto.TaxDeclarationFormDTO;
import com.engine.salary.entity.taxdeclaration.dto.TaxDeclarationInfoDTO;
import com.engine.salary.entity.taxdeclaration.dto.TaxDeclarationListDTO;
import com.engine.salary.entity.taxdeclaration.param.TaxDeclarationDetailListQueryParam;
import com.engine.salary.entity.taxdeclaration.param.TaxDeclarationListQueryParam;
import com.engine.salary.entity.taxdeclaration.param.TaxDeclarationSaveParam;
import com.engine.salary.service.TaxDeclarationExcelService;
import com.engine.salary.service.TaxDeclarationService;
import com.engine.salary.service.impl.TaxDeclarationExcelServiceImpl;
import com.engine.salary.service.impl.TaxDeclarationServiceImpl;
import com.engine.salary.util.ResponseResult;
import com.engine.salary.util.SalaryDateUtil;
import com.engine.salary.util.page.PageInfo;
import com.engine.salary.wrapper.TaxDeclarationDetailWrapper;
import com.engine.salary.wrapper.TaxDeclarationWrapper;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;


@Slf4j
public class TaxDeclarationController {

    private TaxDeclarationService getService(User user) {
        return ServiceUtil.getService(TaxDeclarationServiceImpl.class, user);
    }

    private TaxDeclarationWrapper getTaxDeclarationWrapper(User user) {
        return ServiceUtil.getService(TaxDeclarationWrapper.class, user);
    }

    private TaxDeclarationExcelService getTaxDeclarationExcelService(User user) {
        return  ServiceUtil.getService(TaxDeclarationExcelServiceImpl.class, user);
    }

    private TaxDeclarationDetailWrapper getTaxDeclarationDetailWrapper(User user) {
        return ServiceUtil.getService(TaxDeclarationDetailWrapper.class, user);
    }

    //个税申报表列表
    @POST
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    public String list(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxDeclarationListQueryParam queryParam){
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<TaxDeclarationListQueryParam, PageInfo<TaxDeclarationListDTO>>(user).run(getTaxDeclarationWrapper(user)::listPage, queryParam);
    }

    @POST
    @Path("/withDrawTaxDeclaration")
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteTaxDeclaration(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxDeclarationSaveParam param) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, String>(user).run(getTaxDeclarationWrapper(user)::withDrawTaxDeclaration, param.getTaxDeclarationId());
    }


    //个税申报表表单
    @GET
    @Path("/getForm")
    @Produces(MediaType.APPLICATION_JSON)
    public String getForm(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam(value = "id") Long id) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, TaxDeclarationFormDTO>(user).run(getTaxDeclarationWrapper(user)::getForm, id);
    }

    //个税申报表相关信息
    @GET
    @Path("/getTaxDeclarationInfo")
    @Produces(MediaType.APPLICATION_JSON)
    public String getTaxDeclarationInfo(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam(value = "taxDeclarationId") Long taxDeclarationId) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, TaxDeclarationInfoDTO>(user).run(getTaxDeclarationWrapper(user)::getTaxDeclarationInfoById, taxDeclarationId);
    }

    //个税申报表生成
    @POST
    @Path("/save")
    @Produces(MediaType.APPLICATION_JSON)
    public String save(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxDeclarationSaveParam param) {
        User user = HrmUserVarify.getUser(request, response);
        param.setSalaryMonth(SalaryDateUtil.String2YearMonth(param.getSalaryMonthStr()));
        return new ResponseResult<TaxDeclarationSaveParam, Long>(user).run(getTaxDeclarationWrapper(user)::save, param);
    }

    //个税申报表详情列表
    @POST
    @Path("/detail/list")
    @Produces(MediaType.APPLICATION_JSON)
    public String listTaxDeclarationDetail(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxDeclarationDetailListQueryParam param) {
        User user = HrmUserVarify.getUser(request, response);
        param.setTaxDeclarationId(Long.parseLong(param.getTaxDeclarationIdStr()));
        return new ResponseResult<TaxDeclarationDetailListQueryParam, PageInfo>(user).run(getTaxDeclarationDetailWrapper(user)::listPage, param);
    }

    //个税申报表相关信息
    @GET
    @Path("/export")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response exportTaxDeclaration(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam(value = "taxDeclarationId") Long taxDeclarationId) {
        try {
            User user = HrmUserVarify.getUser(request, response);
            XSSFWorkbook workbook = getTaxDeclarationExcelService(user).exportTaxDeclaration(taxDeclarationId);

            String fileName = "个税申报表" + LocalDate.now();
            try {
                fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            StreamingOutput output = outputStream -> {
                workbook.write(outputStream);
                outputStream.flush();
            };
            response.setContentType("application/octet-stream");
            return Response.ok(output).header("Content-disposition", "attachment;filename=" + fileName).header("Cache-Control", "no-cache").build();
        } catch (Exception e) {
            log.error("个税申报表导出异常", e);
            throw e;
        }
    }
}
